package com.czk.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.czk.common.constant.AuthServerConstant;
import com.czk.common.exception.BizCodeEnum;
import com.czk.common.utils.R;
import com.czk.common.utils.RandomUtil;
import com.czk.common.vo.MemberResponseVo;
import com.czk.gulimall.auth.feign.MemberFeignService;
import com.czk.gulimall.auth.feign.ThirdPartyFeignService;
import com.czk.gulimall.auth.vo.UserLoginVo;
import com.czk.gulimall.auth.vo.UserRegistVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/2/23 21:30
 */
@Controller
public class LoginController {
    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private MemberFeignService memberFeignService;
    /**
     * 登录页
     *
     * @return
     */
    @GetMapping("/login.html")
    public String login(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        // 是否登陆过
        if (attribute == null){
            return "index";
        }
        return "redirect:http://gulimall.com";
    }

    /**
     * 注册页
     *
     * @return
     */
    @GetMapping("/reg.html")
    public String reg() {
        return "reg";
    }

    /**
     * 发送短信
     *
     * @param phone
     * @return
     */
    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) {
        if (StringUtils.isEmpty(phone)) {
            phone = "15723315609";
        }
        // todo 1 接口防刷


        // 2 验证码的再次校验
        // 现在redis中取 key sms:code:phone
        String code = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (code != null) {
            long parseLong = Long.parseLong(code.split("_")[1]);
            if (System.currentTimeMillis() - parseLong < 60 * 1000) {
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        code = RandomUtil.getSixBitRandom() + "_" + System.currentTimeMillis();
        // 2min有效
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code, 2L, TimeUnit.MINUTES);
        thirdPartyFeignService.sendCode(phone, code.split("_")[0]);
        return R.ok("发送成功");
    }

    /**
     * 注册
     * 表单提交不需要@RequestBody
     *
     * @param vo                 注册实体
     * @param bindingResult      表单jsr330校验收集的结果
     * @param redirectAttributes 重定向携带数据 利用session原理，将数据存到session中 只要调到下一个页面中，取出后就会删除掉
     *                           有分布式session共享问题
     * @return
     */
    @PostMapping("/regist")
    public String registry(@Valid UserRegistVo vo, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
        if (bindingResult.hasErrors()) {
            Map<String, String> collect = bindingResult.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, DefaultMessageSourceResolvable::getDefaultMessage));
            // 转发
            redirectAttributes.addFlashAttribute("errors", collect);
            //
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        // 注册
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            String codeTemp = s.split("_")[0];
            if (Objects.equals(codeTemp, code)) {
                // 删除验证码
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                // 验证码通过，注册
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0) {
                    // 成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
                    Map<String, Object> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
            } else {
                // 验证码错误
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession httpSession) {
        //
        R login = memberFeignService.login(vo);
        if (login.getCode() == 0) {
            JSONObject data = (JSONObject) login.getData("data", new TypeReference<Object>() {
            });
            MemberResponseVo memberResponseVo = JSON.toJavaObject(data, MemberResponseVo.class);
            httpSession.setAttribute(AuthServerConstant.LOGIN_USER,memberResponseVo);
            // 成功
            return "redirect:http://gulimall.com";
        } else {
            Map<String, Object> errors = new HashMap<>();
            errors.put("msg", login.getData("msg", new TypeReference<String>() {
            }));
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
